#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tool.gongju import *
from tool.zhibiao import ma_z, ema_z, atr_z
from tool.MyTT import RSI
from tool.yujingWin import YuyinBobao  # 导入语音播报
quanjukongzhi = {'资金控制': False, '多空开关': 3}


def 全局控制(cl):
    """
    """
    # 数据初始化，
    Close = cl.klines[0].close.values
    Datetime = cl.klines[0].datetime.values
    riqishijian = time_to_datetime(Datetime[-1])
    shijian = int(riqishijian.time().strftime("%H%M%S"))  # 当前时间,格式为161500
    riqi = riqishijian.date().strftime("%Y%m%d")  # 当前日期，格式为20210828
    canshu = [cl.jiaoyiqidong, cl.zhanghu, cl.jiaoyishezhi, cl.openingdata, Datetime]  # 传递给交易函数用于交易

    # 参数设置区
    ss = cl.jiaoyishezhi[5][0]  # 开仓数量
    多空控制 = cl.jiaoyishezhi[5][1]  # 0为停止预警，1为只预警多，2为只预警空，3多空都监控
    资金控制 = cl.jiaoyishezhi[5][2]  # 可用资金到了多少不预警，单位万
    zhanghu = cl.zhanghu[cl.jiaoyishezhi[0][0]]

    # # 全局变量的初始化，为空的时候执行
    if 'kyzj' not in cl.sjb:  # 初始化时执行一次，用于初始化缓存字典
        cl.sjb['kyzj'] = zhanghu.zijin['keyongzijin']
        quanjukongzhi['多空开关'] = 多空控制
        # 用于在软件右键策略字典中查看参数输入说明，和指标输出含义说明
        cl.sjb['参数说明'] = {"1": '策略开关', '2': '多空控制：0为停止预警，1为只预警多，2为只预警空，3多空都监控', '3': '可用资金到了多少不预警，单位万'}
        cl.sjb['输出指标说明'] = {"指标1": '可用资金', '指标2': '资金控制是否满足', '指标3': '无', '指标4': '无'}

    if cl.shangcishijian != Datetime[-1]:  # 更新k线时执行，一般用与计算指标
        zhanghu.query_account()
        cl.sjb['kyzj'] = zhanghu.zijin['keyongzijin']
        if cl.sjb['kyzj'] < 资金控制*10000:
            quanjukongzhi['资金控制'] = True
        else:
            quanjukongzhi['资金控制'] = False

    return cl.sjb['kyzj'], quanjukongzhi['资金控制'], quanjukongzhi['多空开关'], 0


def 策略预警1(cl):
    """
    做多信号：MA3 上穿 MA9 同时 收盘价大于 MA240
    做空信号：MA3 下穿 MA9 同时 收盘价小于 MA240
    平多信号：（MA3下穿 MA9  卖出多单止盈） 或者     （ 收盘价小于MA3和MA9相交前的某一定时间内最低值 ）  或者 （ 收盘价小于MA240 卖出多单止损）
    平空信号：（MA3上穿 MA9  卖出空单止盈） 或者      （ 收盘价大于MA3和MA9相交前的某一定时间内最高值 ）  或者   （收盘价大于MA240 卖出空单止损）

    根据交叉点可以做个加仓位和减仓位
    多单3日均线拐头向下，但还没死叉9日，就要减仓
    随后调整几根线后再次向上就可以加仓了
    """
    # 数据初始化，
    Close = cl.klines[0].close.values
    Open = cl.klines[0].open.values
    Datetime = cl.klines[0].datetime.values
    riqishijian = time_to_datetime(Datetime[-1])
    shijian = int(riqishijian.time().strftime("%H%M%S"))  # 当前时间,格式为161500
    riqi = riqishijian.date().strftime("%Y%m%d")  # 当前日期，格式为20210828
    canshu = [cl.jiaoyiqidong, cl.zhanghu, cl.jiaoyishezhi, cl.openingdata, Datetime]  # 传递给交易函数用于交易

    # 参数设置区
    ss = cl.jiaoyishezhi[5][0]  # 开仓数量
    ma1zq = cl.jiaoyishezhi[5][1]  # ma3周期
    ma2zq = cl.jiaoyishezhi[5][2]  # ma3周期
    ma3zq = cl.jiaoyishezhi[5][3]  # ma240周期
    kuazhouqitjkg = True
    预警内容 = cl.jiaoyishezhi[5][4]
    zhanghu = cl.zhanghu[cl.jiaoyishezhi[0][0]]
    heyue = cl.jiaoyishezhi[3][0]  # 交易的合约
    # heyue = GetProduct(heyue) + '9999'
    pos = cl.openingdata['kaicangzhuangtai'] * cl.openingdata['kaicangshuliang']

    # # 全局变量的初始化，为空的时候执行
    if 'bz' not in cl.sjb:  # 初始化时执行一次，用于初始化缓存字典
        cl.sjb['bz'] = True
        cl.sjb['理论持仓状态'] = 0
        cl.sjb['软件名'] = "ruanjian3."
        cl.sjb['开仓时间'] = time.time()
        # 用于在软件右键策略字典中查看参数输入说明，和指标输出含义说明
        cl.sjb['参数说明'] = {"1": '策略开关', '2': '均线周期1', '3': '均线周期2', '4': '均线周期3', '5': '跨日线周期条件开关未用',
                          '6': '预警内容'}
        cl.sjb['输出指标说明'] = {"指标1": '均线值1', '指标2': '均线值2', '指标3': '30周期rsi最大', '指标4': '30周期rsi最小'}

    # # 指标计算区
    ma1 = ma_z(Close, ma1zq)
    ma2 = ma_z(Close, ma2zq)
    # ma3 = ma_z(Close, ma3zq)
    rsi = RSI(Close, 6)
    rsi30max = max(rsi[-30:])
    rsi30min = min(rsi[-30:])

    rkx = kuazhouqi_1d(cl.klines[0], 15)
    rxdtj = True
    rxktj = True
    if kuazhouqitjkg and len(rkx) > ma2zq:
        ma1d = ma_z(rkx.close.values, ma1zq)
        ma2d = ma_z(rkx.close.values, ma2zq)
        rxdtj = ma1d[-1] > ma2d[-1]
        rxktj = ma1d[-1] < ma2d[-1]


    # # 账户持仓获取
    # ccss = chazhaoheyue_duiyingchicang(zhanghu.df_cc, heyue)  # 获取该合约持仓
    # if len(ccss) == 2:
    #     ccss = ccss[0]+ccss[1]  # 求出净持仓
    # else:
    #     ccss = ccss[0]
    #
    # # 账户持仓放入显示
    # if ccss != pos:
    #     MubiaoCangwei4_bxd(ccss, Close[-1], canshu)

    if cl.shangcishijian != Datetime[-1]:  # 更新k线时执行，一般用与计算指标
        cl.sjb['bz'] = True

    # 0为停止预警，1为只预警多，2为只预警空，3多空都监控
    if cl.jiaoyiqidong:

        if time.time()-cl.sjb['开仓时间'] > 60 and quanjukongzhi['多空开关'] != 0 and quanjukongzhi['资金控制'] == False:
            # 开仓
            if quanjukongzhi['多空开关'] != 2 and pos <= 0 and ma1[-1] > ma2[-1] and \
                    ma1[-2] < ma2[-2] and Close[-1] > Open[-1] and rsi30max > 80 and rxdtj:  # Close[-1] > ma3[-1] and
                cl.sjb['bz'] = False
                cl.sjb['开仓时间'] = time.time()
                Buy(ss, Close[-1], canshu)  # 开多
                shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + " 开多")
                YuyinBobao(预警内容 + '开多')
            else:
                if quanjukongzhi['多空开关'] != 1 and pos >= 0 and ma1[-1] < ma2[-1] and \
                        ma1[-2] > ma2[-2] and Close[-1] < Open[-1] and rsi30min < 20 and rxktj:  # Close[-1] < ma3[-1] and
                    cl.sjb['bz'] = False
                    cl.sjb['开仓时间'] = time.time()
                    SellShort(ss, Close[-1], canshu)  # 开空
                    shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + " 开空")
                    YuyinBobao(预警内容+'开空')

            # 加仓

            # 减仓
            if pos > 1 and ma1[-2] > ma2[-3] and ma1[-2] < ma1[-3] and ma1[-3] < ma1[-4]:
                cl.sjb['bz'] = False
                cl.sjb['开仓时间'] = time.time()
                shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "多减仓")
                YuyinBobao(预警内容 + '多减仓')
            else:
                if pos < -1 and ma1[-2] < ma2[-3] and ma1[-2] > ma1[-3] and ma1[-3] > ma1[-4]:
                    cl.sjb['bz'] = False
                    cl.sjb['开仓时间'] = time.time()
                    shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "空减仓")
                    YuyinBobao(预警内容 + '空减仓')

            # 平仓
        if time.time()-cl.sjb['开仓时间'] > 60:
            if pos > 0 and (ma1[-1] < ma2[-1] and ma1[-2] > ma2[-2]):  # (Close[-1] < ma3[-1] and Close[-2] > ma3[-2]) or
                cl.sjb['bz'] = False
                cl.sjb['开仓时间'] = time.time()
                Sell(0, Close[-1], canshu)  # 平多
                shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "平多")
                YuyinBobao(预警内容 + '平多')
            else:
                if pos < 0 and (
                        ma1[-1] > ma2[-1] and ma1[-2] < ma2[-2]):  # ((Close[-1] > ma3[-1] and Close[-2] < ma3[-2]) or
                    cl.sjb['bz'] = False
                    cl.sjb['开仓时间'] = time.time()
                    BuyToCover(0, Close[-1], canshu)  # 平空
                    shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "平空")
                    YuyinBobao(预警内容 + '平空')

    # time.strftime('%H:%M:%S', time.localtime(cl.sjb['开仓时间']))
    return ma1[-1], ma2[-1], rxdtj, rxktj


def 策略预警2(cl):
    """
    做多信号：MA3 上穿 MA9 同时 收盘价大于 MA240
    做空信号：MA3 下穿 MA9 同时 收盘价小于 MA240
    平多信号：（MA3下穿 MA9  卖出多单止盈） 或者     （ 收盘价小于MA3和MA9相交前的某一定时间内最低值 ）  或者 （ 收盘价小于MA240 卖出多单止损）
    平空信号：（MA3上穿 MA9  卖出空单止盈） 或者      （ 收盘价大于MA3和MA9相交前的某一定时间内最高值 ）  或者   （收盘价大于MA240 卖出空单止损）

    根据交叉点可以做个加仓位和减仓位
    多单3日均线拐头向下，但还没死叉9日，就要减仓
    随后调整几根线后再次向上就可以加仓了
    """
    # 数据初始化，
    Close = cl.klines[0].close.values
    Open = cl.klines[0].open.values
    Datetime = cl.klines[0].datetime.values
    riqishijian = time_to_datetime(Datetime[-1])
    shijian = int(riqishijian.time().strftime("%H%M%S"))  # 当前时间,格式为161500
    riqi = riqishijian.date().strftime("%Y%m%d")  # 当前日期，格式为20210828
    canshu = [cl.jiaoyiqidong, cl.zhanghu, cl.jiaoyishezhi, cl.openingdata, Datetime]  # 传递给交易函数用于交易

    # 参数设置区
    ss = cl.jiaoyishezhi[5][0]  # 开仓数量
    ma1zq = cl.jiaoyishezhi[5][1]  # ma3周期
    ma2zq = cl.jiaoyishezhi[5][2]  # ma3周期
    ma3zq = cl.jiaoyishezhi[5][3]  # ma240周期
    kuazhouqitjkg = False
    预警内容 = cl.jiaoyishezhi[5][4]
    zhanghu = cl.zhanghu[cl.jiaoyishezhi[0][0]]
    heyue = cl.jiaoyishezhi[3][0]  # 交易的合约
    # heyue = GetProduct(heyue) + '9999'
    pos = cl.openingdata['kaicangzhuangtai'] * cl.openingdata['kaicangshuliang']

    # # 全局变量的初始化，为空的时候执行
    if 'bz' not in cl.sjb:  # 初始化时执行一次，用于初始化缓存字典
        cl.sjb['bz'] = True
        cl.sjb['理论持仓状态'] = 0
        cl.sjb['软件名'] = "ruanjian3."
        cl.sjb['开仓时间'] = time.time()
        # 用于在软件右键策略字典中查看参数输入说明，和指标输出含义说明
        cl.sjb['参数说明'] = {"1": '策略开关', '2': '均线周期1', '3': '均线周期2', '4': '均线周期3', '5': '跨日线周期条件开关未用',
                          '6': '预警内容'}
        cl.sjb['输出指标说明'] = {"指标1": '均线值1', '指标2': '均线值2', '指标3': '30周期rsi最大', '指标4': '30周期rsi最小'}

    # # 指标计算区
    ma1 = ma_z(Close, ma1zq)
    ma2 = ma_z(Close, ma2zq)
    ma3 = ma_z(Close, ma3zq)
    rsi = RSI(Close, 6)
    rsi30max = max(rsi[-30:])
    rsi30min = min(rsi[-30:])

    rkx = kuazhouqi_1d(cl.klines[0], 15)
    rxdtj = True
    rxktj = True
    if kuazhouqitjkg and len(rkx) > ma2zq:
        ma1d = ma_z(rkx.close.values, ma1zq)
        ma2d = ma_z(rkx.close.values, ma2zq)
        rxdtj = ma1d[-1] > ma2d[-1]
        rxktj = ma1d[-1] < ma2d[-1]


    # # 账户持仓获取
    # ccss = chazhaoheyue_duiyingchicang(zhanghu.df_cc, heyue)  # 获取该合约持仓
    # if len(ccss) == 2:
    #     ccss = ccss[0]+ccss[1]  # 求出净持仓
    # else:
    #     ccss = ccss[0]
    #
    # # 账户持仓放入显示
    # if ccss != pos:
    #     MubiaoCangwei4_bxd(ccss, Close[-1], canshu)

    if cl.shangcishijian != Datetime[-1]:  # 更新k线时执行，一般用与计算指标
        cl.sjb['bz'] = True

    # 0为停止预警，1为只预警多，2为只预警空，3多空都监控
    if cl.jiaoyiqidong:

        if time.time()-cl.sjb['开仓时间'] > 60 and quanjukongzhi['多空开关'] != 0 and quanjukongzhi['资金控制'] == False:
            # 开仓
            if quanjukongzhi['多空开关'] != 2 and pos <= 0 and ma1[-1] > ma2[-1] and \
                    ma1[-2] < ma2[-2] and Close[-1] > Open[-1] and rsi30max > 80 and Close[-1] > ma3[-1]:
                cl.sjb['bz'] = False
                cl.sjb['开仓时间'] = time.time()
                Buy(ss, Close[-1], canshu)  # 开多
                shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + " 开多")
                YuyinBobao(预警内容 + '开多')
            else:
                if quanjukongzhi['多空开关'] != 1 and pos >= 0 and ma1[-1] < ma2[-1] and \
                        ma1[-2] > ma2[-2] and Close[-1] < Open[-1] and rsi30min < 20 and Close[-1] < ma3[-1]:
                    cl.sjb['bz'] = False
                    cl.sjb['开仓时间'] = time.time()
                    SellShort(ss, Close[-1], canshu)  # 开空
                    shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + " 开空")
                    YuyinBobao(预警内容+'开空')

            # 加仓

            # 减仓
            if pos > 1 and ma1[-2] > ma2[-3] and ma1[-2] < ma1[-3] and ma1[-3] < ma1[-4]:
                cl.sjb['bz'] = False
                cl.sjb['开仓时间'] = time.time()
                shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "多减仓")
                YuyinBobao(预警内容 + '多减仓')
            else:
                if pos < -1 and ma1[-2] < ma2[-3] and ma1[-2] > ma1[-3] and ma1[-3] > ma1[-4]:
                    cl.sjb['bz'] = False
                    cl.sjb['开仓时间'] = time.time()
                    shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "空减仓")
                    YuyinBobao(预警内容 + '空减仓')

        # 平仓
        if cl.shangcishijian != Datetime[-1]:
            if pos > 0 and (ma1[-2] < ma2[-2] and ma1[-3] > ma2[-3]):  # (Close[-1] < ma3[-1] and Close[-2] > ma3[-2]) or
                cl.sjb['bz'] = False
                cl.sjb['开仓时间'] = time.time()
                Sell(0, Close[-1], canshu)  # 平多
                shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "平多")
                YuyinBobao(预警内容 + '平多')
            else:
                if pos < 0 and (
                        ma1[-2] > ma2[-2] and ma1[-3] < ma2[-3]):  # ((Close[-1] > ma3[-1] and Close[-2] < ma3[-2]) or
                    cl.sjb['bz'] = False
                    cl.sjb['开仓时间'] = time.time()
                    BuyToCover(0, Close[-1], canshu)  # 平空
                    shujuku.publish(cl.sjb['软件名'] + 'celue', heyue+','+预警内容 + "平空")
                    YuyinBobao(预警内容 + '平空')

    # time.strftime('%H:%M:%S', time.localtime(cl.sjb['开仓时间']))
    return ma1[-1], ma2[-1], rxdtj, rxktj


